<template>
	<div>
		<el-row :gutter="20">
			<el-col :span="8">
				<el-card shadow="hover" class="mgb20" style="height: 252px">
					<div class="user-info">
						<el-avatar :size="120" :src="imgurl" />
						<div class="user-info-cont">
							<div class="user-info-name">{{ name }}</div>
							<div>{{ role }}</div>
						</div>
					</div>
					<div class="user-info-list">
						登录时间：
						<span>{{ loginTime }}</span>
					</div>
					<div class="user-info-list">
						访问方式：
						<span>{{ ipType }}</span>
					</div>
					<div class="user-info-list">
						登录IP：
						<span>&nbsp;&nbsp;&nbsp;&nbsp;{{ loginIp }}</span>
					</div>
				</el-card>
				<el-card shadow="hover" style="height: 252px">
					<template #header>
						<div class="clearfix">
							<span>系统负载</span>
						</div>
					</template>
					CPU使用率
					<el-progress v-for="item in sysLog" :percentage="item.sysCpu" :indeterminate="true" :duration="5" color="#42b983"></el-progress>
					磁盘使用率
					<el-progress v-for="item in sysLog" :percentage="item.sysDisk" :indeterminate="true" :duration="5" color="#f1e05a"></el-progress>
					物理内存使用率
					<el-progress v-for="item in sysLog" :percentage="item.sysPhyMey" :indeterminate="true" :duration="5"></el-progress>
					虚拟缓存使用率
					<el-progress v-for="item in sysLog" :percentage="item.sysVirMey" :indeterminate="true" :duration="5" color="#f56c6c"></el-progress>
				</el-card>
			</el-col>
			<el-col :span="16">
				<el-row :gutter="20" class="mgb20">
					<el-col :span="8">
						<el-card shadow="hover" :body-style="{ padding: '0px' }">
							<div class="grid-content grid-con-1">
								<el-icon class="grid-con-icon iconfont el-third-iconzaixianshebei"></el-icon>
								<div class="grid-cont-right">
									<div class="grid-num">{{onLine}}</div>
									<div>在线设备</div>
								</div>
							</div>
						</el-card>
					</el-col>
					<el-col :span="8">
						<el-card shadow="hover" :body-style="{ padding: '0px' }">
							<div class="grid-content grid-con-2">
								<el-icon class="grid-con-icon iconfont el-third-iconlixianshebei"></el-icon>
								<div class="grid-cont-right">
									<div class="grid-num">{{offLine}}</div>
									<div>离线设备</div>
								</div>
							</div>
						</el-card>
					</el-col>
					<el-col :span="8">
						<el-card shadow="hover" :body-style="{ padding: '0px' }">
							<div class="grid-content grid-con-3">
								<el-icon class="grid-con-icon iconfont el-third-iconfilesystemreport"></el-icon>
								<div class="grid-cont-right">
									<div class="grid-num">{{exception}}</div>
									<div>异常设备</div>
								</div>
							</div>
						</el-card>
					</el-col>
				</el-row>
				<el-card shadow="hover" style="height: 403px">
					<template #header>
						<div class="clearfix">
							<span>设备运行状况</span>
						</div>
					</template>
					<el-table :data="deviceData" height="320" style="width: 100%">
						<el-table-column
								prop="ID"
								label="设备编号"
								width="200">
						</el-table-column>
						<el-table-column
								prop="name"
								label="设备名称"
								width="200">
						</el-table-column>
						<el-table-column
								prop="type"
								label="设备类型"
								width="200">
						</el-table-column>
						<el-table-column
								prop="room"
								label="教室"
								width="200">
						</el-table-column>
						<el-table-column
								prop="workStatus"
								label="设备状态"
								width="200">
						</el-table-column>
						<el-table-column
								prop="onlineTime"
								label="时间"
								width="200">
						</el-table-column>
					</el-table>
				</el-card>
			</el-col>
		</el-row>
		<el-row :gutter="20">
			<el-col :span="12">
				<el-card shadow="hover">
					<schart ref="bar" class="schart" canvasId="bar" :options="options"></schart>
				</el-card>
			</el-col>
			<el-col :span="12">
				<el-card shadow="hover">
					<schart ref="line" class="schart" canvasId="line" :options="options2"></schart>
				</el-card>
			</el-col>
		</el-row>
	</div>
</template>

<script setup lang="ts" name="homepage">
import Schart from 'vue-schart';
import {onMounted, onUnmounted, reactive, ref} from 'vue';
import imgurl from '../assets/img/img.jpg';
import API from "../utils/axios";
import {Socket} from "net";

const name = localStorage.getItem('ms_username');
const role: string = localStorage.getItem('ms_role') === 'admin' ? '超级管理员' : '普通用户';
const loginTime = localStorage.getItem('login_time');
const loginIp = localStorage.getItem('login_ip');
const ipType = localStorage.getItem('ip_type')


// 建立WebSocket连接
const ws = new WebSocket("ws://localhost:8085/webSocket");
ws.onopen = function (event){
	console.log('建立连接');
}
ws.onclose = function (event){
	console.log('连接关闭');
}
ws.onmessage= function (event){
	// 进行弹窗提醒或其他操作
	try {
		// 将接收到的 JSON 字符串转换成 JavaScript 对象
		const message = JSON.parse(event.data);
		// 设备数据处理
		if (message.dataType == "设备数据"){
			handleDeviceData(message);
		}else if (message.dataType == "系统日志"){
			handleSystemLog(message);
		}
	} catch (error) {
		console.error('JSON 解析出错', error);
	}
}
ws.onerror= function (){
	alert('websocket通信发生错误！')
};

// socket设备数据处理
const handleDeviceData = (message : any) => {
	// 获取更新数据
	const socketData = message.dataBody;
	const newData = socketData.map((item : any) => {
		let workStatus  = '';
		if (item.deviceWorkStatus == 0){
			workStatus = '离线';
		}else{
			workStatus = '在线';
		}
		return {ID : item.deviceNumber, name: item.deviceName, type : item.deviceType, room : item.roomName,
			workStatus : workStatus, onlineTime : item.deviceOnlineTime};
	})
	deviceData.value = newData;
}

const sysLog = ref([]);
const handleSystemLog = (message : any) => {
	const socketData = message.dataBody;
	const newData = socketData.map((item : any) => {
		return {sysCpu : item.sysCpu, sysDisk : item.sysDisk, sysPhyMey : item.sysPhyMey, sysVirMey : item.sysVirMey}
	})
	sysLog.value = newData;
}

onMounted(() => {
	// 挂载组件时初始化系统参数
	const initData = [{sysCpu : 0, sysDisk : 0, sysPhyMey : 0, sysVirMey : 0}];
	sysLog.value = initData;
	// 定时获取设备在线数量
	setInterval(() => {
		getDeviceWorkNumber();
	},50000),
	// 异步获取数据
	(async () => {
		await getDeviceWorkNumber();
		await getLightDevice();
		await getAnnouncement();
	})()
})

// 组件被关闭时关闭WebSocket连接
onUnmounted(() => {
	ws.close();
})

// 获取未读系统通告
let announcementData = ref([]);
const getAnnouncement = () => {
	API.post("/LogFile/getAnnouncement")
			.then((res) => {
				const data = res.data.data.map((item : any) => {
					return {uuid : item.announcementUuid, message : item.announcementType+item.announcementMessage, time : item.announcementTime}
				})
				announcementData.value = data;
				localStorage.setItem("newMessage", announcementData.value.length);
			})
			.catch((err) => {return err})
}

// 获取不同工作状态下的设备数量
const onLine = ref();
const offLine = ref();
const exception = ref();
const getDeviceWorkNumber = () => {
  API.post("/DeviceController/getDeviceWorkStatus")
			.then((res) => {
				onLine.value = res.data.data.onLine;
				offLine.value = res.data.data.offLine;
				exception.value = res.data.data.exception;
			})
			.catch((err) => {return err})
}

// 灯光设备数据
let deviceData = ref([]);
// 获取灯光设备数据
const getLightDevice = () => {
	API.post('/DeviceController/getAllDevice')
			.then((res) => {
				deviceData.value  = res.data.data.map((item : any) => {
					let workStatus  = '';
					if (item.deviceStatus == 0){
						workStatus = '离线';
					}else{
						workStatus = '在线';
					}
					return { ID : item.deviceNumber, name: item.deviceName, type : item.deviceType, room : item.roomName,
						workStatus : workStatus, onlineTime : item.deviceOnlineTime}
				})
			})
			.catch((err) => {
				return err
			})
};

const options = {
	type: 'bar',
	title: {
		text: '最近一周终端设备在线数量变化图'
	},
	xRorate: 25,
	labels: ['周一', '周二', '周三', '周四', '周五'],
	datasets: [
		{
			label: '灯',
			data: [12, 16, 19, 19, 21]
		},
		{
			label: '温湿度传感器',
			data: [32, 33, 29, 21, 46]
		},
		{
			label: '火焰传感器',
			data: [36, 33, 37, 43, 43]
		}
	]
};
const options2 = {
	type: 'line',
	title: {
		text: '24小时教室照明数据变化图'
	},
	labels: ['0点', '4点', '8点', '12点', '16点', '20点'],
	datasets: [
		{
			label: '环境亮度',
			data: [0, 620, 3600, 6100, 5700, 2460]
		}
	]
};
const todoList = reactive([
	{
		ID:'001',
		name:'灯',
		place:'6101',
		status: '正常',
		time:'2023-12-11 15:30',
	},
	{
		ID:'002',
		name:'灯',
		place:'6102',
		status: '正常',
		time:'2023-12-11 15:30',
	},
	{
		ID:'003',
		name:'灯',
		place:'6103',
		status: '已离线',
		time:'2023-12-11 15:30',
	},
	{
		ID:'004',
		name:'烟雾传感器',
		place:'6104',
		status: '正常',
		time:'2023-12-11 15:30',
	},
	{
		ID:'005',
		name:'温湿度传感器',
		place:'6105',
		status: '异常',
		time:'2023-12-11 15:30',
	},
	{
		ID:'006',
		name:'灯',
		place:'6106',
		status: '已离线',
		time:'2023-12-11 15:30',
	},
	{
		ID:'007',
		name:'光敏传感器',
		place:'6107',
		status: '正常',
		time:'2023-12-11 15:30',
	},
	{
		ID:'008',
		name:'火焰传感器',
		place:'6108',
		status: '异常',
		time:'2023-12-11 15:30',
	},
	{
		ID:'009',
		name:'灯',
		place:'6109',
		status: '正常',
		time:'2023-12-11 15:30',
	}
]);
</script>

<style scoped>
.el-row {
	margin-bottom: 20px;
}

.grid-content {
	display: flex;
	align-items: center;
	height: 100px;
}

.grid-cont-right {
	flex: 1;
	text-align: center;
	font-size: 14px;
	color: #999;
}

.grid-num {
	font-size: 30px;
	font-weight: bold;
}

.grid-con-icon {
	font-size: 50px;
	width: 100px;
	height: 100px;
	text-align: center;
	line-height: 100px;
	color: #fff;
}

.grid-con-1 .grid-con-icon {
	background: rgb(45, 140, 240);
}

.grid-con-1 .grid-num {
	color: rgb(45, 140, 240);
}

.grid-con-2 .grid-con-icon {
	background: rgb(100, 213, 114);
}

.grid-con-2 .grid-num {
	color: rgb(100, 213, 114);
}

.grid-con-3 .grid-con-icon {
	background: rgb(242, 94, 67);
}

.grid-con-3 .grid-num {
	color: rgb(242, 94, 67);
}

.user-info {
	display: flex;
	align-items: center;
	padding-bottom: 15px;
	border-bottom: 2px solid #ccc;
	margin-bottom: 15px;
}

.user-info-cont {
	padding-left: 50px;
	flex: 1;
	font-size: 14px;
	color: #999;
}

.user-info-cont div:first-child {
	font-size: 30px;
	color: #222;
}

.user-info-list {
	font-size: 14px;
	color: #999;
	line-height: 25px;
}

.user-info-list span {
	margin-left: 70px;
}

.mgb20 {
	margin-bottom: 20px;
}

.schart {
	width: 100%;
	height: 300px;
}
</style>
